package api_vsys

import (
	"encoding/json"
	"io"
	"restapi/module"
	"strconv"
	"strings"

	"github.com/gin-gonic/gin"
)

func respond400(g *gin.Context, msg string) { g.JSON(400, gin.H{"code": 400, "message": msg}) }

func decodeJSON(g *gin.Context, dst interface{}) bool {
	body, err := io.ReadAll(g.Request.Body)
	if err != nil {
		respond400(g, "读取请求体失败")
		return false
	}
	if len(body) == 0 {
		respond400(g, "请求体不能为空")
		return false
	}
	if err := json.Unmarshal(body, dst); err != nil {
		respond400(g, "JSON格式错误")
		return false
	}
	return true
}

// ================= 手动校验函数 =================
// 返回 (ok=false, msg=原因) 表示失败；ok=true 表示通过

// 创建虚拟系统校验
func validateCreateVsys(req *module.CreateVsysRequest) (bool, string) {
	if req.Name == "" {
		return false, "创建虚拟系统:虚拟系统名称为空"
	}
	if len(req.Interfaces) == 0 {
		return false, "创建虚拟系统:接口名数组为空"
	}
	// 过滤空字符串接口名
	cleaned := make([]string, 0, len(req.Interfaces))
	for _, iface := range req.Interfaces {
		iface = strings.TrimSpace(iface)
		if iface == "" {
			return false, "创建虚拟系统:接口名数组中存在空接口"
		}
		cleaned = append(cleaned, iface)
	}
	req.Interfaces = cleaned
	return true, ""
}

// 删除虚拟系统校验
func validateDeleteVsys(req *module.DeleteVsysRequest) (bool, string) {
	if len(req.Id) == 0 {
		return false, "删除虚拟系统:虚拟系统数组为空"
	}
	for _, id := range req.Id {
		if id <= 0 {
			return false, "删除虚拟系统:虚拟系统数组存在无效值"
		}
	}
	return true, ""
}

// 更新虚拟系统校验（当前只允许改描述和接口列表）
func validateUpdateVsys(req *module.UpdateVsysRequest) (bool, string) {
	if len(req.Interfaces) == 0 {
		return false, "编辑虚拟系统:接口数组为空"
	}
	cleaned := make([]string, 0, len(req.Interfaces))
	for _, iface := range req.Interfaces {
		iface = strings.TrimSpace(iface)
		if iface == "" {
			return false, "编辑虚拟系统:接口数组中存在空接口"
		}
		cleaned = append(cleaned, iface)
	}
	req.Interfaces = cleaned
	return true, ""
}

// 列表查询校验
func validateListVsys(pageSize, pageNum int) (bool, string) {
	if pageSize <= 0 {
		return false, "查询虚拟系统列表:页大小必须大于0"
	}
	if pageNum <= 0 {
		return false, "查询虚拟系统列表:页码必须大于0"
	}
	return true, ""
}

// 解析虚拟系统列表查询参数（与策略列表统一风格）
func parseListVsysQuery(g *gin.Context, req *module.ListVsysRequest) {
	if pageSizeStr := g.Query("pageSize"); pageSizeStr != "" {
		req.PageSize, _ = strconv.Atoi(pageSizeStr)
	}
	if pageNumStr := g.Query("pageNum"); pageNumStr != "" {
		req.PageNum, _ = strconv.Atoi(pageNumStr)
	}
	req.Name = g.Query("name")
}
